<template>
  <el-dialog
      :title="form.id ? '编辑学习资源' : '新增学习资源'"
      :visible.sync="show"
      width="600px"
      @close="onClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="资源标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入资源标题"/>
      </el-form-item>
      <el-form-item label="资源类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择资源类型" style="width: 100%">
          <el-option label="文档" :value="1"/>
          <el-option label="视频" :value="2"/>
          <el-option label="音频" :value="3"/>
          <el-option label="图片" :value="4"/>
          <el-option label="链接" :value="5"/>
        </el-select>
      </el-form-item>
      <el-form-item label="专业领域" prop="domain">
        <el-select v-model="form.domain" placeholder="请选择专业领域" style="width: 100%">
          <el-option label="铁道工程" :value="1"/>
          <el-option label="信号控制" :value="2"/>
          <el-option label="机车车辆" :value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="难度等级" prop="level">
        <el-rate
          v-model="form.level"
          :max="5"
          :texts="['初级', '初中级', '中级', '中高级', '高级']"
          show-text
        />
      </el-form-item>
      <el-form-item label="资源描述" prop="description">
        <el-input
          type="textarea"
          v-model="form.description"
          :rows="4"
          placeholder="请输入资源描述"
        />
      </el-form-item>
      <el-form-item label="资源文件" prop="path">
        <el-input
          v-if="form.type === 5"
          v-model="form.path"
          placeholder="请输入资源链接"
        />
        <FileUpload v-else v-model="form.path" @change="handleUploadSuccess"></FileUpload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from "@/api";
import FileUpload from "@/components/UploadFileMultiple.vue";

export default {
  name: "LearningResourceAdd",
  components: {FileUpload},
  data() {
    return {
      show: false,
      loading: false,
      nodeOptions: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      fileList: [],
      form: {
        id: null,
        title: '',
        type: '',
        path: '',
        description: '',
        domain: '',
        level: 1,
        resourceTotalTime: 0,
      },
      rules: {
        title: [
          { required: true, message: '请输入资源标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择资源类型', trigger: 'change' }
        ],
        domain: [
          { required: true, message: '请选择专业领域', trigger: 'change' }
        ],
        level: [
          { required: true, message: '请选择难度等级', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入资源描述', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请上传资源文件或输入资源链接', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (this.form.type === 5 && value) {
                // 验证URL格式
                const urlPattern = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/
                if (!urlPattern.test(value)) {
                  callback(new Error('请输入有效的URL地址'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    getNodeTypeName(type) {
      const types = {
        1: '概念',
        2: '定理',
        3: '公式',
        4: '规则',
        5: '设备',
        6: '技术'
      }
      return types[type] || '-'
    },
    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt100M
    },
    handleUploadSuccess(res, file) {
      this.getMediaDuration(this.form.path)
      this.$message.success('上传成功')
    },
    handleUploadError() {
      this.$message.error('上传失败')
    },
    getMediaDuration(url) {
      // 根据资源类型创建对应的媒体元素
      const media = this.form.type === 2 ? document.createElement('video') : document.createElement('audio')

      // 只加载元数据以提高性能
      media.preload = 'metadata'

      // 设置跨域属性
      media.crossOrigin = 'anonymous'

      return new Promise((resolve) => {
        // 监听元数据加载完成事件
        media.onloadedmetadata = () => {
          if (media.duration && !isNaN(media.duration)) {
            this.form.resourceTotalTime = Math.round(media.duration)
            this.$message.success('已获取媒体时长')
          } else {
            this.form.resourceTotalTime = 0
            this.$message.warning('无法获取媒体时长，将设为0')
          }
          URL.revokeObjectURL(media.src)
          resolve()
        }

        // 监听错误事件
        media.onerror = (e) => {
          console.error('Media load error:', e)
          this.$message.warning('无法获取媒体文件时长，请确保文件格式正确')
          this.form.resourceTotalTime = 0
          URL.revokeObjectURL(media.src)
          resolve()
        }

        // 设置超时处理
        setTimeout(() => {
          this.$message.warning('获取媒体时长超时，请检查文件是否可访问')
          this.form.resourceTotalTime = 0
          URL.revokeObjectURL(media.src)
          resolve()
        }, 5000) // 5秒超时

        // 尝试加载媒体
        try {
          // 如果是本地上传的文件，创建 blob URL
          if (url.startsWith('blob:')) {
            media.src = url
          } else {
            // 如果是远程URL，先通过fetch获取以处理跨域
            fetch(url)
              .then(response => response.blob())
              .then(blob => {
                media.src = URL.createObjectURL(blob)
              })
              .catch(error => {
                console.error('Fetch media error:', error)
                this.$message.error('获取媒体文件失败')
                this.form.resourceTotalTime = 0
                resolve()
              })
          }
        } catch (error) {
          console.error('Media load error:', error)
          this.$message.error('加载媒体文件失败')
          this.form.resourceTotalTime = 0
          resolve()
        }
      })
    },
    open(row) {
      this.show = true
      if (row) {
        this.form = {
          ...row,
          resourceTotalTime: row.resourceTotalTime || 0
        }
        if (row.path && row.type !== 5) {
          this.fileList = [{
            name: row.title,
            url: row.path
          }]
        }
      } else {
        this.form = {
          id: null,
          title: '',
          type: '',
          path: '',
          description: '',
          domain: '',
          level: 1,
          resourceTotalTime: 0,
        }
        this.fileList = []
      }
    },
    onClose() {
      this.show = false
      this.$refs.form.resetFields()
      this.fileList = []
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const submitData = { ...this.form }
          if (![2, 3].includes(submitData.type)) {
            delete submitData.resourceTotalTime
          }

          http.resource[this.form.id ? 'update' : 'create'](submitData).then(() => {
            this.$message.success(this.form.id ? '更新成功' : '创建成功')
            this.onClose()
            this.$emit('success')
          }).catch(error => {
            this.$message.error(error.message || '操作失败')
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.upload-demo {
  .el-upload__tip {
    line-height: 1.2;
    margin-top: 5px;
  }
}
</style>
